package com.xxc.hs.funActivity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.xxc.hs.R;
import com.xxc.hs.funActivity.waring.ScreenshotManager;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;

@SuppressWarnings("ALL")
public class WaringActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private ScreenshotAdapter adapter;
    private List<ScreenshotItem> screenshotList = new ArrayList<>();
    private ScreenshotManager screenshotManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_waring);

        try {
            // 初始化截图管理器
            screenshotManager = new ScreenshotManager(this, this);

            // 初始化RecyclerView
            recyclerView = findViewById(R.id.recyclerView);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            adapter = new ScreenshotAdapter(screenshotList);
            recyclerView.setAdapter(adapter);

            // 加载截图
            loadScreenshots();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadScreenshots() {
        File screenshotsDir = screenshotManager.getScreenshotsDirectory();
        if (!screenshotsDir.exists() || !screenshotsDir.isDirectory()) {
            return;
        }

        // 获取所有JPG图片
        File[] files = screenshotsDir.listFiles((dir, name) ->
                name.toLowerCase().endsWith(".jpg") || name.toLowerCase().endsWith(".jpeg"));

        if (files != null && files.length > 0) {
            // 按文件修改时间排序（最新在前）
            Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());

            screenshotList.clear();
            for (File file : files) {
                String fileName = file.getName();
                String timestamp = extractTimestampFromFileName(fileName);
                String displayTime = formatTimestampToNewFormat(timestamp);
                screenshotList.add(new ScreenshotItem(file, displayTime));
            }
            adapter.notifyDataSetChanged();
        }
    }

    /** 从文件名中提取时间戳（匹配waring_年月日_时分秒.jpg格式） */
    private String extractTimestampFromFileName(String fileName) {
        if (fileName.startsWith("waring_") && fileName.endsWith(".jpg")) {
            return fileName.substring("waring_".length(), fileName.lastIndexOf("."));
        }
        return fileName;
    }


    private String formatTimestampToNewFormat(String timestamp) {
        try {
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy年MM月dd日_HH时mm分ss秒", Locale.CHINA);
            Date date = inputFormat.parse(timestamp);
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
            return outputFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return timestamp;
        }
    }

    /** 格式化时间戳为标准显示格式 */
    private String formatTimestamp(String timestamp) {
        try {
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy年MM月dd日_HH时mm分ss秒", Locale.CHINA);
            Date date = inputFormat.parse(timestamp);
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
            return outputFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return timestamp;
        }
    }

    /** 截图项数据类 */
    private static class ScreenshotItem {
        File imageFile;
        String displayTime;

        ScreenshotItem(File imageFile, String displayTime) {
            this.imageFile = imageFile;
            this.displayTime = displayTime;
        }
    }

    /** RecyclerView适配器 */
    private class ScreenshotAdapter extends RecyclerView.Adapter<ScreenshotAdapter.ScreenshotViewHolder> {

        private List<ScreenshotItem> itemList;

        ScreenshotAdapter(List<ScreenshotItem> itemList) {
            this.itemList = itemList;
        }

        @Override
        public ScreenshotViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_screenshot, parent, false);
            return new ScreenshotViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ScreenshotViewHolder holder, int position) {
            ScreenshotItem item = itemList.get(position);

            // 使用Glide加载图片
            Glide.with(holder.itemView.getContext())
                    .load(item.imageFile)
                    .centerCrop()
                    .into(holder.imageView);

            holder.timeTextView.setText(item.displayTime);

            // 点击查看大图
            holder.itemView.setOnClickListener(v -> openImagePreview(item.imageFile));
        }

        @Override
        public int getItemCount() {
            return itemList.size();
        }

        /** 打开图片预览 */
        private void openImagePreview(File imageFile) {
            Uri imageUri = FileProvider.getUriForFile(
                    WaringActivity.this,
                    getPackageName() + ".fileprovider",
                    imageFile
            );

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(imageUri, "image/*");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            }
        }

        class ScreenshotViewHolder extends RecyclerView.ViewHolder {
            ImageView imageView;
            TextView timeTextView;

            ScreenshotViewHolder(View itemView) {
                super(itemView);
                imageView = itemView.findViewById(R.id.imageView);
                timeTextView = itemView.findViewById(R.id.timeTextView);
            }
        }
    }

    /** 处理权限申请结果 */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        screenshotManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}